from django.conf import settings
from QQLoginTool.QQtool import OAuthQQ
# Create your views here.
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView,CreateAPIView
from rest_framework.response import Response
from rest_framework_jwt.settings import api_settings

from carts.utils import merge_cart_cookie_to_redis
from .serializers import OauthSerializer
from .models import OAuthQQUser
from itsdangerous import TimedJSONWebSignatureSerializer as TJS

# get qq/authorization/$  login_url
class QQAuthURLView(APIView):
    # serializer_class =
    def get(self,request):
        # 获取参数state
        state = request.query_params.get('state','/')

        # 返回ＱＱ登录页面ＵＲＬ
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,client_secret=settings.QQ_CLIENT_SECRET,redirect_uri=settings.QQ_REDIRECT_URI,state=state)
        login_url = oauth.get_qq_url()

        return Response({'login_url':login_url})


class QQAuthUserView(CreateAPIView):

    serializer_class = OauthSerializer

    # get  code  qq/user/  openid,token,username,user_id
    def get(self,request):
        # 1.获取openid

        # 获取code参数
        code = request.query_params.get('code')
        if not code:
            return Response({'error:':'缺少code'},status=status.HTTP_400_BAD_REQUEST)

        # 2、通过code获取access_token，
        # res = requests.get('https://graph.qq.com/oauth2.0/token',
        #                    params={'grant_type': 'authorization_code', 'client_id': settings.QQ_CLIENT_ID,
        #                            'client_secret': settings.QQ_CLIENT_SECRET, 'code': code,
        #                            'redirect_uri': settings.QQ_REDIRECT_URI})
        #
        # data=res.text

        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,client_secret=settings.QQ_CLIENT_SECRET,redirect_uri=settings.QQ_REDIRECT_URI)

        try:
            # 　通过code参数获取access_token参数
            access_token = oauth.get_access_token(code)

            # 通过access_token获取openid
            openid = oauth.get_open_id(access_token)

        except Exception as e:
            return Response({'message':'QQ服务器异常'},status=status.HTTP_503_SERVICE_UNAVAILABLE)

        # 2.判定ＱＱ是否绑定手机用户：
            #　绑定过返回保存登录状态的token，username,user_id
            #　未绑定返回加密过的openid
        try:
            # 绑定
            # 如果已经绑定写错跳到绑定页面再绑定一次，
            # 数据库中就会有２条一样的数据，get方法就会找不到报错
            qq_user = OAuthQQUser.objects.get(openid=openid)


        except:
            # 未绑定
            # 以SECRET_KEY为加密方式
            tjs = TJS(settings.SECRET_KEY,300)
            # dumps为加密操作，对openid加密
            token = tjs.dumps({'openid':openid}).decode()
            return Response({'access_token':token})

        # 绑定过找到绑定的用户对象
        user = qq_user.user

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        response = Response({
            'username':user.username,
            'user_id':user.id,
            'token':token,
        })

        response = merge_cart_cookie_to_redis(request, user, response)

        return response

    # post   mobile,password,sms_code,access_token
    # /qq/user   username,user_id,token,
    def post(self,request,*args, **kwargs):

        response = super().post(request, *args, **kwargs)

        # 还未登录不能request.user获取user,只能拿序列化器中已经在数据库查询出的user
        response =  merge_cart_cookie_to_redis(request, self.user, response)
        return response


